import React, { useState, useEffect, useRef } from 'react';
import './SearchInput.css';

const SearchInput = ({ onSearch, isLoading, suggestions = [], onSuggestionClick }) => {
  const [inputValue, setInputValue] = useState('');
  const [showSuggestions, setShowSuggestions] = useState(false);
  const inputRef = useRef(null);
  const suggestionsRef = useRef(null);

  // 处理输入变化
  const handleInputChange = (e) => {
    const value = e.target.value;
    setInputValue(value);
    setShowSuggestions(value.length > 0 && suggestions.length > 0);
  };

  // 处理搜索提交
  const handleSubmit = (e) => {
    e.preventDefault();
    const trimmedValue = inputValue.trim();
    if (trimmedValue && !isLoading) {
      onSearch(trimmedValue);
      setShowSuggestions(false);
    }
  };

  // 处理建议点击
  const handleSuggestionClick = (suggestion) => {
    setInputValue(suggestion);
    setShowSuggestions(false);
    onSuggestionClick(suggestion);
  };

  // 处理键盘事件
  const handleKeyDown = (e) => {
    if (e.key === 'Escape') {
      setShowSuggestions(false);
    }
  };

  // 点击外部关闭建议列表
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        suggestionsRef.current &&
        !suggestionsRef.current.contains(event.target) &&
        !inputRef.current.contains(event.target)
      ) {
        setShowSuggestions(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 获取占位符文本
  const getPlaceholder = () => {
    const placeholders = [
      '请输入城市名称...',
      '例如：北京、上海、广州',
      '搜索您想了解的城市天气'
    ];
    return placeholders[Math.floor(Math.random() * placeholders.length)];
  };

  return (
    <div className="search-container">
      <form onSubmit={handleSubmit} className="search-form">
        <div className="search-input-wrapper">
          <input
            ref={inputRef}
            type="text"
            value={inputValue}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            onFocus={() => setShowSuggestions(inputValue.length > 0 && suggestions.length > 0)}
            placeholder={getPlaceholder()}
            className="search-input"
            disabled={isLoading}
            maxLength={50}
          />
          <button
            type="submit"
            className="search-button"
            disabled={isLoading || !inputValue.trim()}
            title="搜索天气"
          >
            {isLoading ? (
              <div className="loading-spinner">🔄</div>
            ) : (
              <span className="search-icon">🔍</span>
            )}
          </button>
        </div>

        {/* 搜索建议列表 */}
        {showSuggestions && suggestions.length > 0 && (
          <div ref={suggestionsRef} className="suggestions-list">
            {suggestions.map((suggestion, index) => (
              <div
                key={index}
                className="suggestion-item"
                onClick={() => handleSuggestionClick(suggestion)}
              >
                <span className="suggestion-icon">📍</span>
                <span className="suggestion-text">{suggestion}</span>
              </div>
            ))}
          </div>
        )}
      </form>

      {/* 快捷城市按钮 */}
      <div className="quick-cities">
        <span className="quick-cities-label">热门城市：</span>
        {['北京', '上海', '广州', '深圳'].map((city) => (
          <button
            key={city}
            className="quick-city-btn"
            onClick={() => handleSuggestionClick(city)}
            disabled={isLoading}
          >
            {city}
          </button>
        ))}
      </div>
    </div>
  );
};

export default SearchInput;